<template>
  <div class="sso-login-container">
    <div class="sso-login-box">
      <img src="@/assets/openid.png" alt="OpenIddict logo" class="sso-login-logo" />
      <h1>单点登录</h1>
      <p>OpenIddict认证中心登录</p>
      <el-button type="primary" @click="handleSSOLogin" style="width: 100%;" size="large">
        <img src="@/assets/openid.png" alt="OpenIddict" style="width:20px;height:20px;margin-right:8px;" />
        继续使用 OpenIddict
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useCodeVerifierStore } from '@/store/code-verifier';
import { generateCodeChallenge, generateCodeVerifier } from "@/utils/pkce";
import { useUserStore } from '@/store/user';

const router = useRouter()
const userStore = useUserStore()
const redirectUri = ref(
    window.location.origin + router.resolve({ path: "/callback" }).href
);
let loginWindow = null;


const codeVerifier = ref("");
const codeVerifierStore = useCodeVerifierStore()
const clientId = ref(import.meta.env.VITE_OPENIDDICT_CLIENT_ID);const handleSSOLogin = async() => {
  codeVerifier.value = await generateCodeVerifier();
    const codeChallenge = await generateCodeChallenge(codeVerifier.value);
    // 生成随机state值（防CSRF）
    const state = Math.random().toString(36).substring(2);
    codeVerifierStore.setState(state);
    codeVerifierStore.setCodeVerifier(codeVerifier.value);
    const authUrl =
        `${import.meta.env.VITE_API_BASE_AUTH_URL}/connect/authorize?` +
        `response_type=code` +
        `&client_id=${clientId.value}` +
        `&redirect_uri=${encodeURIComponent(redirectUri.value)}` +
        `&scope=openid profile offline_access` +
        `&state=${state}` +
        `&code_challenge=${codeChallenge}` +
        // `&code_verifier=${codeVerifier.value}` +
        `&code_challenge_method=S256`;
    // window.location.href = authUrl;
    loginWindow = window.open(
        authUrl,
        '_blank',
        'width=900,height=600,menubar=no,toolbar=no,location=no,status=no,resizable=yes,scrollbars=yes'
    );
}

window.addEventListener('message', async (event) => {
  if (event.data && event.data.type === 'auth-success') {
    userStore.addUserInfo(event.data.userInfo, event.data.permissions)
    //跳转至首页
    router.replace({ path: '/' })
  }
})
</script>

<style scoped lang="scss">
.sso-login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f6f8fa;
}

.sso-login-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  padding: 2rem;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(27,31,35,0.12), 0 8px 24px rgba(27,31,35,0.12);
  width: 320px;
}

.sso-login-logo {
  width: 48px;
  height: 48px;
  margin-bottom: 1rem;
}

h1 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 0.5rem;
  text-align: center;
  width: 100%;
}

p {
  font-size: 14px;
  color: #57606a;
  margin-bottom: 1.5rem;
  text-align: center;
}

.sso-footer {
  margin-top: 1rem;
  text-align: center;
}

.sso-footer a {
  font-size: 12px;
  color: #0969da;
  text-decoration: none;
}

.sso-footer a:hover {
  text-decoration: underline;
}
</style>